from cStringIO import StringIO
from ZPublisher.HTTPRequest import record
from types import InstanceType
from csv import DictWriter
from DateTime.DateTime import DateTime, DateTimeError

def parseDate( string ):
    """ 
        Parses a date string and returns a DateTime Object, or None if it could not be parsed 
        (Designed for use in Page Templates, where lack of proper exception handling
         makes catching date errors very messy)    
    """
    
    if not string:   # If no string is specified, return a None
        return None
    
    try:
        return DateTime( string )
    except DateTimeError:  
        # Could not parse the date string, return None
        return None
        


def renderCSV( fields, data, renderHeader = False ):
    """ Renders a CSV with the specified fields from 'data' 
    
        fields: list of keys
        data: list of dictionaries
    """
    
    out = StringIO()
    
    if renderHeader:
        print >> out, '"' + '","'.join( fields ) + '"'
    
    writer = DictWriter( out, fields, extrasaction='ignore' )
    writer.writerows( data )
    return out.getvalue()
    


def serializeRequest(form, recordName=None):
    """ 
        Serializes a request/form into hidden fields 
        i.e. {key:value}
        becomes
            <input name="key" value="value'"/>
    """
    
    out = StringIO()
    
    recordPrefix = recordPostfix = ""
    
    if recordName:
        recordPrefix = "%s." % recordName
        recordPostfix = ":record"
    
    
    for key, value in form.items():
        
        # Simple key => value pair
        if type( value ) is str:
            print >> out, '<input type="hidden" name="%(recordPrefix)s%(key)s%(recordPostfix)s" value="%(value)s"/>\n' % locals()
            
        # key => [value] pair (List of values)
        elif type(value) is list:
            for item in value:
                print >> out, '<input type="hidden" name="%(recordPrefix)s%(key)s:list%(recordPostfix)s" value="%(item)s"/>\n' % locals()
                
        # Recordset- key => {key:value, ...}
        elif type(value) is InstanceType and value.__class__ is record:
            
            # RecordSets are an entire list of key-value pairs in themselves, and we should be able to render them recursively.
            print >> out, serializeRequest( dict(value), recordName=key )
                
                
        else:
            
            # Unknown type, we can't serialize it
            raise "Cannot serialize %s" % `value`
            
                   
    return out.getvalue()                   
        
        